package projects

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"github.com/beego/beego/v2/server/web/pagination"
	"log"
	"strconv"
	"strings"
	"xpms/controllers"
	"xpms/cores"
	"xpms/cores/utils"
)

// 文档管理
type DocController struct {
	controllers.BaseController
}

// @Title 分页查询项目文档数据
// @Description 分页查询项目文档数据
// @Param	id		path 	string	true		"项目id"
// @Param	p		query 	int	true		"第几页"
// @Param	pageoffset		query 	int			"每页数"
// @Param	keyword		query 	string			"关键字"
// @Success 200 {object} projects.ProjectsDocs   int   int  int
// @Failure 403 module not exist
// @router /:id/page [get]
func (u *DocController) Page() {
	page, err := u.GetInt("p")
	if err != nil {
		page = 1
	}
	offset, err := u.GetInt("pageoffset")
	if err != nil {
		offset = 15
	}
	id, err := u.GetInt64(":id")
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "未选择对应的项目" + err.Error()}
		u.ServeJSON()
		return
	}
	keyword := u.GetString("keyword")
	condArr := make(map[string]interface{})
	condArr["projectid"] = id
	condArr["keyword"] = keyword
	countUser := DocPageCountExec(condArr, page, offset)
	paginator := pagination.SetPaginator(u.Ctx, offset, countUser)
	modeData := DocPageExec(condArr, page, offset)
	type data struct {
		Doc      []ProjectsDocs
		Total    int64
		PageNums int
		Page     int
	}
	d := &data{modeData, paginator.Nums(), paginator.PageNums(), paginator.Page()}
	var responseEntity cores.ResponseEntity
	u.Data["json"] = responseEntity.Build(d).Data
	u.Ctx.Output.Status = responseEntity.StatusCode
	u.ServeJSON()
}

type DocDTO struct {
	Projectid  int64 `json:"Projectid,string"`
	Title      string
	Sort       int
	Keyword    string
	Content    string
	Url        string
	Id         int64 `json:"Id,string"`
	Userid     int64
	Attachment string
}

// @Title Create doc
// @Description create doc
// @Param	body		body 	projects.DocDTO	true		"body for doc content"
// @Success 200 {string} projects.ProjectsDocs.Id
// @Failure 403 body is empty
// @router / [post]
func (u *DocController) Create() {
	var f DocDTO
	err := json.Unmarshal(u.Ctx.Input.RequestBody, &f)
	// 开始校验输入值
	valid := validation.Validation{}
	valid.Required(f.Projectid, "Projectid").Message("项目名称不能为空")
	b, err := valid.Valid(&f)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	userid := u.BaseController.UserUserId
	//雪花算法ID生成
	id := utils.SnowFlakeId()
	// todo 可以修改成 只转化一次
	f.Id = id
	f.Userid = userid
	err = AddDocs(f)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息添加成功", "id": fmt.Sprintf("%d", id)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息添加失败" + err.Error()}
	}
	u.ServeJSON()
}

// @Title Update doc
// @Description  Update doc
// @Param	id		path 	string	true		"doc id"
// @Param	body		body 	projects.DocDTO	true		"body for doc content"
// @Success 200 {string} 更新成功
// @Failure 403 body is empty
// @router /:id [put]
func (u *DocController) Update() {
	ids, err := u.GetInt64(":id")
	if err != nil || ids <= 0 {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "你选择更新的项目为空"}
		u.ServeJSON()
		return
	}
	var f DocDTO
	err = json.Unmarshal(u.Ctx.Input.RequestBody, &f)
	// 开始校验输入值
	valid := validation.Validation{}
	b, err := valid.Valid(&f)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	err = UpdateDocs(ids, f)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息修改成功", "id": fmt.Sprintf("%d", ids)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息修改失败" + err.Error()}
	}
	u.ServeJSON()
}

// @Title Get
// @Description get doc  by id
// @Param	id		path 	string	true		"The key for doc"
// @Success 200 {object} projects.ProjectsDocs
// @Failure 403 :id is empty
// @router /:id [get]
func (u *DocController) Get() {
	uid := u.GetString(":id")
	if uid != "" {
		var responseEntity cores.ResponseEntity
		int64, err := strconv.ParseInt(uid, 10, 64)
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
			return
		}
		modeData, err := GetProjectDocs(int64)
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
		} else {
			u.Data["json"] = responseEntity.Build(modeData).Data
			u.Ctx.Output.Status = responseEntity.StatusCode
		}
	}
	u.ServeJSON()
}
